from urllib import urlencode
from urllib2 import urlopen
import json, pprint

class AlloCine(object):
	def __init__(self):
		self.domain = "api.allocine.fr"
		self.format_string = "%s"

	@property
	def search_url(self):
		domain = self.domain.strip('/')
		return "http://%s/xml/search?%%s" % domain

	@property
	def movie_url(self):
		domain = self.domain.strip('/')
		return "http://%s/xml/movie?%%s" % domain

	def search(self, string):
		params = {
			'q': self.format_string % string,
			'partner' : 8,
			'json': 1,
		}

		url = self.search_url % urlencode(params)
		page = urlopen(url)
		return json.load(page)

	def get_movie(self, id):
		params = {
			'code': id,
			'partner' : 1,
			'json': 1,
#			"profile" : "large",
		}

		url = self.movie_url % urlencode(params)
		page = urlopen(url)
		return json.load(page)

if __name__ == "__main__":
	webapi = AlloCine()
	result = webapi.search("avatar")
	movies = result["feed"]["movie"]
	print "Found %d results" % len(movies)
#	pprint.pprint(movies)
	pprint.pprint(movies[0])
	movie = webapi.get_movie(movies[0]["code"])["movie"]
	pprint.pprint(movie)
#	print movie["synopsis"]
#	print movie["synopsisShort"]
	page = urlopen(movies[0]["poster"]["href"])
	fd = file("avatar.jpg", "wb+")
	fd.write(page.read())
	fd.close()


